package org.example.controller;

import org.example.pojo.MailVo;
import org.example.pojo.UmsUser;
import org.example.service.IUmsUserService;
import org.example.util.ResultCode;
import org.example.util.ResultData;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/mail")
public class MailController {
    @Resource
    JavaMailSender javaMailSender;
    @Resource
    IUmsUserService userService;
    @PostMapping("/send")
    ResultData send(MailVo mailVo) throws MessagingException, UnsupportedEncodingException {
        String x = "";
        x+=(int)(Math.random()*10000);
        UmsUser byPhone = userService.getByPhone(mailVo.getTo());
        if(byPhone == null) return ResultData.failed(ResultCode.FAILED,"邮箱不正确");
        mailVo.setContent( x );
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        mailVo.setFrom("2106261058@qq.com");
        mailVo.setPersonal("2106261058");
        mailVo.setSubject( "标题:产生式系统" );
        mailVo.setContent( "验证码：" + x);

        helper.setFrom(mailVo.getFrom(),mailVo.getPersonal());
        helper.setTo(mailVo.getTo());
        helper.setSubject(mailVo.getSubject());
        helper.setText(mailVo.getContent(),true);
        javaMailSender.send(mimeMessage);
        System.out.println(x);
        return ResultData.success( x );
    }
}
